<template>
  <div class="app-container">

    <!--    <el-row :gutter="10" class="mb8">-->
    <!--      <el-col :span="1.5">-->
    <!--        <el-button-->
    <!--            type="warning"-->
    <!--            plain-->
    <!--            icon="Close"-->
    <!--            @click="handleClose"-->
    <!--        >关闭-->
    <!--        </el-button>-->
    <!--      </el-col>-->
    <!--    </el-row>-->
    <el-card>
      <template #header>基本信息</template>
      <el-descriptions :column="4" title="" border>
        <el-descriptions-item
            :rowspan="2"
            :width="140"
            label="头像"
            align="center"
        >
          <el-image
              style="width: 100px; height: 100px"
              :src="baseUrl + assessmentInfo.headLogo"
          />
        </el-descriptions-item>
        <el-descriptions-item label="姓名">{{ assessmentInfo.elderName }}</el-descriptions-item>
        <el-descriptions-item label="养老院">{{ assessmentInfo.nursinghome }}</el-descriptions-item>
        <el-descriptions-item label="性别">
          <div v-if="assessmentInfo.sex==0">男</div>
          <div v-if="assessmentInfo.sex==1">女</div>
          <div v-if="assessmentInfo.sex==2">未知</div>
        </el-descriptions-item>
        <el-descriptions-item label="年龄">{{ assessmentInfo.age }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{ assessmentInfo.idNo }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-card style="margin-top: 20px">
      <template #header>评估详情</template>
      <div class="problem-box">
        <div class="num-box">
          <div class="num_" v-for="(item,index) in tabList" :key="index"
               :class="[ tabIndex === index ? 'active' : '',item.ifComplete==true && tabIndex !== index ? 'active-gre' : '' ]"
               @click="chooseTab(index,item)">
            {{ index + 1 }}
          </div>
        </div>
        <div class="num-text" :style="tabIndex==0 ? 'transform: scale(1.003)':''">{{ tabText }}</div>
      </div>

      <div style="margin-top: 20px;width: 60%">
        <el-form ref="answerRef" :model="form" :rules="rules" label-position="top" label-width="auto">
          <el-form-item v-for="(item,index) in questionList" :key="index" :label="item.title"
                        :required="item.isRequired==1">
            <el-input v-if="item.questionType=='单行文本框' || item.questionType=='自动计算得分'" v-model="item.answer"
                      placeholder="请输入内容"/>
            <!--          单选-->
            <el-radio-group v-model="item.answer" v-if="item.questionType=='单选'" @change="calculate(item.ifAnswer)">
              <el-radio
                  v-for="(item1, index1) in item.optionList"
                  :key="index1"
                  :label="item1"
              >{{ item1 }}
              </el-radio>
              <el-input
                  v-if="item.showInput==1 && form.answer==item.optionList[item.optionList.length-1]"
                  v-model="item.answerRemark" placeholder="请输入内容"/>
            </el-radio-group>
            <!--          多选-->
            <el-checkbox-group v-if="item.questionType=='多选'" v-model="item.checkAnswer">
              <el-checkbox
                  v-for="(item1, index1) in item.optionList"
                  :key="index1"
                  :label="item1"
                  :value="item1"
              >{{ item1 }}
              </el-checkbox>
            </el-checkbox-group>
            <!--          日期选择框-->
            <el-date-picker v-if="item.questionType=='日期选择框'"
                            v-model="item.answer"
                            type="datetime"
                            placeholder="请选择日期"
                            format="YYYY-MM-DD HH:mm:ss"
                            style="width: 100%"
            />
            <!--          表格-->
            <div v-if="item.questionType=='表格'">
              <el-table
                  :data="tableData"
                  border
                  size="small"
              >
                <el-table-column
                    v-for="(column, index1) in item.optionList"
                    :key="index1"
                    :prop="index1"
                    :label="column"
                    align="center"
                    width="90"
                >
                  <template #default="scope">
                    <el-input type="text" v-model="scope.row[index1]"/>
                  </template>
                </el-table-column>
                <el-table-column
                    label="操作"
                    align="center"
                    width="90"
                >
                  <template #default="scope">
                    <el-button type="danger"
                               link @click="deleteRow(scope.$index)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-button type="primary" style="width: 100px;margin: 10px auto;"
                         @click="addRow(item.optionList.length)">添加行
              </el-button>
            </div>
            <el-input v-if="item.questionType=='多行文本框'" v-model="form.answer" type="textarea"
                      placeholder="请输入内容"/>
          </el-form-item>
          <el-form-item label="分数"
                        v-if="questionInfo.title && questionInfo.title.includes('老年人能力最终等级')">
            <el-input v-model="form.remark" placeholder="请输入内容"/>
          </el-form-item>
        </el-form>
        <div style="text-align: center">
          <el-button @click="handleClose">返 回</el-button>
          <el-button type="primary" @click="addAnswers">修 改</el-button>
        </div>
      </div>
    </el-card>
    <!--    @selection-change="handleSelectionChange"
          <el-table-column type="selection" width="55" align="center"/>-->
    <!--    <el-table v-loading="loading" :data="answerList" border>-->
    <!--      <el-table-column label="序号" align="center" type="index" width="80"/>-->
    <!--      <el-table-column label="问卷标题" align="center" prop="surveyName" :show-overflow-tooltip="true"/>-->
    <!--      <el-table-column label="问卷题目名称" align="center" prop="questionName" :show-overflow-tooltip="true"/>-->
    <!--      <el-table-column label="作答内容" align="center" prop="content" :show-overflow-tooltip="true">-->
    <!--        <template #default="scope">-->
    <!--          <div v-if="scope.row.questionType=='表格'">-->
    <!--            <div v-if="scope.row.content">-->
    <!--              <el-table-->
    <!--                  :data="parseTableData(scope.row.content)"-->
    <!--                  border-->
    <!--                  style="width: 100%; margin-top: 10px;"-->
    <!--                  size="small"-->
    <!--              >-->
    <!--                <el-table-column-->
    <!--                    v-for="(column, index) in scope.row.optionList"-->
    <!--                    :key="index"-->
    <!--                    :prop="index"-->
    <!--                    :label="column"-->
    <!--                    align="center"-->
    <!--                >-->
    <!--                  <template #default="scope">-->
    <!--                    {{ scope.row[index] }}-->
    <!--                  </template>-->
    <!--                </el-table-column>-->
    <!--              </el-table>-->
    <!--            </div>-->
    <!--          </div>-->
    <!--          <div v-else>{{ scope.row.content }}</div>-->
    <!--        </template>-->
    <!--      </el-table-column>-->
    <!--      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true"/>-->
    <!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
    <!--        <template #default="scope">-->
    <!--          <el-button-->
    <!--              type="text"-->
    <!--              icon="Edit"-->
    <!--              @click="handleUpdate(scope.row)"-->
    <!--          >修改-->
    <!--          </el-button>-->
    <!--          &lt;!&ndash;          <el-button&ndash;&gt;-->
    <!--          &lt;!&ndash;              type="text"&ndash;&gt;-->
    <!--          &lt;!&ndash;              icon="Delete"&ndash;&gt;-->
    <!--          &lt;!&ndash;              @click="handleDelete(scope.row)"&ndash;&gt;-->
    <!--          &lt;!&ndash;          >删除&ndash;&gt;-->
    <!--          &lt;!&ndash;          </el-button>&ndash;&gt;-->
    <!--        </template>-->
    <!--      </el-table-column>-->
    <!--    </el-table>-->

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改答卷详情对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body :close-on-click-modal="false">
      <el-form ref="answerRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="作答内容">
          <!--          单选-->
          <el-radio-group v-model="form.content" v-if="questionInfo.questionType=='单选'">
            <el-radio
                v-for="(item, index) in questionInfo.optionList"
                :key="index"
                :label="item"
            >{{ item }}
            </el-radio>
            <el-input
                v-if="questionInfo.showInput==1 && form.content==questionInfo.optionList[questionInfo.optionList.length-1]"
                v-model="form.remark" placeholder="请输入内容"/>
          </el-radio-group>
          <!--          多选-->
          <el-checkbox-group v-else-if="questionInfo.questionType=='多选'" v-model="checkboxContent">
            <el-checkbox
                v-for="(item, index) in questionInfo.optionList"
                :key="index"
                :label="item"
                :value="item"
            >{{ item }}
            </el-checkbox>
          </el-checkbox-group>
          <!--          表格-->
          <div v-else-if="questionInfo.questionType=='表格'">
            <el-table
                :data="tableData"
                border
                size="small"
            >
              <el-table-column
                  v-for="(column, index) in questionInfo.optionList"
                  :key="index"
                  :prop="index"
                  :label="column"
                  align="center"
                  width="90"
              >
                <template #default="scope">
                  <el-input type="text" v-model="scope.row[index]"/>
                </template>
              </el-table-column>
              <el-table-column
                  label="操作"
                  align="center"
                  width="90"
              >
                <template #default="scope">
                  <el-button type="danger"
                             link @click="deleteRow(scope.$index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button type="primary" style="width: 100px;margin: 10px auto;"
                       @click="addRow(questionInfo.optionList.length)">添加行
            </el-button>
          </div>
          <el-input v-else v-model="form.content" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="分数"
                      v-if="questionInfo.title && questionInfo.title.includes('老年人能力最终等级')">
          <el-input v-model="form.remark" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Answer">
import {listAnswer, getAnswer, delAnswer, addAnswer, updateAnswer} from "@/views/pg/answerSheet/api/answer";
import {listAllSurvey} from "@/views/pg/questionnaire/api/survey.js";
import {getQuestion, listAllQuestion} from "@/views/pg/questionnaire/api/question.js";
import {getAssessment, listAllAssessment} from "@/views/pg/evaluate/api/assessment.js";
import {useRoute} from 'vue-router';
import {saveBatchAnswer} from "@/views/pg/answerSheet/api/answer.js";

const baseUrl = import.meta.env.VITE_APP_BASE_API
const {proxy} = getCurrentInstance();
const route = useRoute();

const assId = computed(() => route.query.id)
const answerList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const assList = ref([]);
const surveyList = ref([]);
const questionList = ref([]);
const questionInfo = ref({});
const checkboxContent = ref([]);
const tableData = ref([]);
// 评估人员信息
const assessmentInfo = ref({})
const tabList = ref([])
const tabIndex = ref(0)
const tabText = ref('')

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    assId: null,
    surveyId: null,
    questionId: null,
    content: null,
    remark: null,
  },
  rules: {}
});

const {queryParams, form, rules} = toRefs(data);

getAssList();
getSurveyList();

onMounted(() => {
  console.log("pagePath:answer")
  // queryParams.value.assId = assId.value
  // getList();
  getAssInfo()
})

function calculate(ifAnswer) {
  // 自动计算得分
  if (questionList.value.length > 1 && questionList.value.find(item => item.questionType == '自动计算得分')) {
    let score = 0
    for (var i = 0; i < questionList.value.length; i++) {
      if (i != questionList.value.length - 1) {
        if (questionList.value[i].answer != null && questionList.value[i].answer && questionList.value[i]
            .answer.includes('分')) {
          let list = questionList.value[i].answer.split('分')
          if (list && list.length > 0) score += Number(list[0])
        }
      }
    }
    questionList.value[questionList.value.length - 1].answer = score
  }
}

// 获取评估信息
function getAssInfo() {
  tabIndex.value = 0
  getAssessment(assId.value).then(res => {
    assessmentInfo.value = res.data
    tabList.value = res.data.surveyList
    if (tabList.value.length > 0) {
      tabText.value = res.data.surveyList[0].title
      getQuestionList(res.data.surveyList[0].id)
    }
  })
}

// 选择tab
function chooseTab(index, item) {
  tabIndex.value = index
  tabText.value = item.title
  getQuestionList(item.id)
}

function addAnswers() {
  questionList.value.forEach(item => {
    if (item.questionType == '表格') {
      item.answer = JSON.stringify(tableData.value)
    }
  })
  saveBatchAnswer({
    assId: assessmentInfo.value.id,
    questionList: questionList.value
  }).then(res => {
    proxy.$message.success('修改成功')
    getAssInfo()
  })
}

// 解析表格数据，将原始数据转换为表格行数据
function parseTableData(content) {
  try {
    const data = JSON.parse(content);
    if (Array.isArray(data) && data.length > 0) {
      // 将对象数组转换为表格行数据
      return data;
    }
    return [];
  } catch (e) {
    console.error('解析表格数据失败:', e);
    return [];
  }
}

/** 查询评估列表 */
function getAssList() {
  listAllAssessment().then(res => {
    assList.value = res.data;
  })
}

/** 获取问卷列表 */
function getSurveyList() {
  listAllSurvey().then(res => {
    surveyList.value = res.data;
  })
}

/** 获取问卷题目列表 */
function getQuestionList(surveyId) {
  listAllQuestion({
    surveyId: surveyId,
    assId: assId.value
  }).then(res => {
    questionList.value = res.data;
    questionList.value.forEach(item => {
      if (item.questionType == '表格') {
        if (item.answer) tableData.value = JSON.parse(item.answer)
      }
    })
  })
}

/** 查询答卷详情列表 */
function getList() {
  loading.value = true;
  listAnswer(queryParams.value).then(response => {
    answerList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    assId: null,
    surveyId: null,
    questionId: null,
    content: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    deleteStatus: "1"
  };
  proxy.resetForm("answerRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加答卷详情";
}

/** 返回按钮操作 */
function handleClose() {
  const obj = {path: "/evaluate/assessment"}
  proxy.$tab.closeOpenPage(obj)
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getQuestionInfo(row.questionId)
  getAnswer(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改答卷详情";
    tableData.value = parseTableData(form.value.content);
  });
}

// 获取问题详情
function getQuestionInfo(questionId) {
  getQuestion(questionId).then(res => {
    questionInfo.value = res.data
  })
}

// 添加行
function addRow() {
  tableData.value.push({})
}

// 删除行
function deleteRow(index) {
  tableData.value.splice(index)
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["answerRef"].validate(valid => {
    if (valid) {
      if (tableData.value && tableData.value.length > 0) form.value.content = JSON.stringify(tableData.value)
      if (form.value.id != null) {
        updateAnswer(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addAnswer(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除？').then(function () {
    return delAnswer(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('answerSheet/answer/export', {
    ...queryParams.value
  }, `answer_${new Date().getTime()}.xlsx`)
}
</script>
<style scoped>
.input_ {
  border: 1px solid #DBDDE3;
}

.problem-box {
  margin-top: 20px;
}

.num-box {
  display: flex;
  align-items: center;
  position: relative;
  /* 移除原来的 border-bottom */
}

/* 使用伪元素创建底部边框 */
.num-box::after {
  content: '';
  position: absolute;
  bottom: -1px;
  /* 调整位置使其与子元素底部对齐 */
  left: 0;
  right: 0;
  height: 1px;
  background-color: #19949B;
  z-index: 1;
}

.num_ {
  width: 36px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  color: #19949B;
  border-radius: 5px 5px 0 0;
  border: 1px solid #19949B;
  /* 保留底部边框 */
  border-bottom: none;
  margin-right: 5px;
  position: relative;
  z-index: 2;
  transition: all 0.3s ease;
  background: #fff;
  /* 添加背景色确保覆盖父级边框 */
  cursor: pointer;
}

.active {
  /* 选中时移除底部边框，露出父级边框 */
  border-bottom: 1px solid #fff !important;
  background: rgba(25, 148, 155, 0.1);
  transform: scale(1.05);
}

.active-gre {
  background: #55ac55;
  color: #fff;
  transform: scale(1.05);
}

.num-text {
  color: #3A3A3A;
  background: rgba(25, 148, 155, 0.1);
  border: 1px solid #19949B;
  border-top: 0px;
  padding: 10px 20px;
  box-sizing: border-box;
  border-radius: 0 0 5px 5px;
}
</style>